// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-2ga6780q302b7f4a'
}) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID || 'test_openid_001' // 使用测试openId作为后备
  const { equipmentId } = event
  
  console.log('函数开始执行，参数:', event)
  console.log('openId:', openId)
  console.log('equipmentId:', equipmentId)
  
  // 参数校验
  if (!equipmentId) {
    return {
      code: -1,
      message: '缺少必要参数：equipmentId'
    }
  }
  
  // 不使用事务先进行初步检查
  try {
    console.log('开始检查设备ID是否有效')
    // 检查equipment是否存在
    const equipCheck = await db.collection('equipment').doc(equipmentId).get()
    console.log('设备检查结果:', equipCheck)
    
    console.log('开始检查用户')
    // 检查user是否存在
    const userCheck = await db.collection('users').where({ openId: openId }).get()
    console.log('用户检查结果:', userCheck)
    
    if (userCheck.data.length === 0) {
      return {
        code: -1,
        message: '用户不存在，请先登录'
      }
    }
    
    // 开始数据库事务
    const transaction = await db.startTransaction()
    
    try {
      // 1. 获取用户信息，检查信用分
      const { data: users } = await transaction.collection('users').where({ openId: openId }).get()
      if (users.length === 0) {
        await transaction.rollback() // 回滚事务
        return {
          code: -1,
          message: '用户不存在，请先登录'
        }
      }
      
      const user = users[0]
      console.log('获取到用户:', user)
      
      // 检查用户信用分是否低于门槛
      if (user.creditScore < 60) {
        await transaction.rollback() // 回滚事务
        return {
          code: -1,
          message: `信用分不足，当前信用分${user.creditScore}，最低需要60分才能借用装备`
        }
      }
      
      // 2. 获取装备信息
      const { data: equipment } = await transaction.collection('equipment').doc(equipmentId).get()
      if (!equipment) {
        await transaction.rollback() // 回滚事务
        return {
          code: -1,
          message: '装备不存在'
        }
      }
      
      console.log('获取到设备:', equipment)
      
      // 3. 检查装备状态
      if (equipment.status !== '可借用') {
        await transaction.rollback() // 回滚事务
        return {
          code: -1,
          message: '该装备当前不可借用'
        }
      }
      
      // 4. 检查用户信用分
      if (user.creditScore < equipment.creditRequired) {
        await transaction.rollback() // 回滚事务
        return {
          code: -1,
          message: `信用分不足，需要${equipment.creditRequired}分，当前为${user.creditScore}分`
        }
      }
      
      // 5. 创建借用订单
      const borrowTime = db.serverDate()
      const returnDeadline = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000) // 默认7天后归还
      
      console.log('开始创建订单')
      const orderResult = await transaction.collection('orders').add({
        data: {
          userId: user._id,
          openId: openId,
          equipmentId: equipment._id,
          equipmentName: equipment.name,
          equipmentImage: equipment.imageUrl,
          borrowTime: borrowTime,
          returnDeadline: returnDeadline,
          actualReturnTime: null,
          status: '借用中',
          createTime: borrowTime
        }
      })
      
      console.log('订单创建结果:', orderResult)
      const orderId = orderResult._id
      
      // 6. 更新装备状态
      console.log('开始更新设备状态')
      await transaction.collection('equipment').doc(equipment._id).update({
        data: {
          status: '已借出',
          currentOrderId: orderId
        }
      })
      
      // 提交事务
      console.log('提交事务')
      await transaction.commit()
      
      return {
        code: 0,
        data: {
          orderId,
          borrowTime,
          returnDeadline
        },
        message: '借用成功'
      }
    } catch (err) {
      // 发生错误，回滚事务
      console.error('事务内部错误:', err)
      if (transaction) {
        await transaction.rollback()
      }
      
      return {
        code: -1,
        message: '借用失败: ' + err.message
      }
    }
  } catch (err) {
    console.error('初始检查错误:', err)
    return {
      code: -1,
      message: '借用失败: ' + err.message
    }
  }
} 